package com.netty.esc.service.action;

import com.alibaba.fastjson.JSONObject;
import com.netty.esc.common.enums.WSProtocolTypeEM;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: Etan96
 * @CreateDate: 2022/8/29 20:07
 * @Description: 函数执行中心
 */
@Slf4j
@Component
public class ActionCenter{

    private ThreadPoolExecutor threadPoolExecutor;

    public ActionCenter(ThreadPoolExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    /**
     * 执行函数
     * @param code 函数注解code
     * @param context ChannelContext
     * @param jsonObject 参数jsonObject
     * @return true：执行   false：未执行
     */
    public boolean execute(String code, ChannelHandlerContext context, JSONObject jsonObject) {
        ActionProcessor processor = ApplicationEventCenter.processors.get(code);
        if (processor == null) {
            log.info("不处理的协议：code = " + code + ", TaskDesc = " + getActionDesc(code));
            return false;
        } else {
            CompletableFuture.runAsync(() -> processor.execute(context, jsonObject),threadPoolExecutor);
            return true;
        }
    }

    private String getActionDesc(String code) {
        return WSProtocolTypeEM.matchType(code).desc();
    }

}
